/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 *
 * 			http://www.ouer.com/
 *
 * ========================================================
 */

package com.simon.mengkou.ui.dialog;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

import com.ouertech.android.agm.lib.base.constant.CstFile;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilFile;
import com.ouertech.android.agm.lib.base.utils.UtilLog;
import com.ouertech.android.agm.lib.base.utils.UtilMD5;
import com.ouertech.android.agm.lib.base.utils.UtilPackage;
import com.ouertech.android.agm.lib.base.utils.UtilStorage;
import com.ouertech.android.agm.lib.ui.base.BaseDialog;
import com.simon.mengkou.R;
import com.simon.mengkou.data.bean.base.UpdateInfo;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.utils.UtilOuer;

import java.io.File;


/**
 * @author : Zhenshui.Xia
 * @date   : 2014-8-11
 * @desc   : 升级提示对话框
 */
public class AppUpdateDialog extends BaseDialog {
	// 应用更新下载通知ID
    private static final int APP_DOWNLOAD_NOTIFY_ID = 0;

	private Activity mActivity;
    private UpdateInfo mInfo;

    public AppUpdateDialog(Activity activity, UpdateInfo info) {
        super(activity);
        this.mActivity = activity;
        this.mInfo = info;
    }

    public AppUpdateDialog(Activity activity, UpdateInfo info, int theme){
        super(activity, theme);
        this.mActivity = activity;
        this.mInfo = info;
    }

    @Override
	protected void initLayout() {

	}


	@Override
	protected void initViews() {
		setTitle(R.string.upgrade_update_title);
		setMessage(mInfo.getMsg());

		if(mInfo.isForceUpdate()) {//强制升级
			 setSingle(R.string.upgrade_update);

			 setOnSingleListener(new OnSingleListener() {

				@Override
				public void onSingle() {
					update();
				}
			});

		} else {//可选升级
			setDouble(R.string.upgrade_cancel, R.string.upgrade_update);

			setOnDoubleListener(new OnLeftListener() {

				@Override
				public void onLeft() {
					cancel();
				}
			}, new OnRightListener() {

				@Override
				public void onRight() {
					update();
				}
			});
		}
	}

	 @Override
	public void onBackPressed() {
		super.onBackPressed();
		if(mInfo.isForceUpdate()) {
			mActivity.finish();
		}
	}

	/**
	 * 下载升级应用
	 */
	private void update() {
		String fileName = UtilMD5.getStringMD5(mInfo.getUrl()) + CstFile.SUFFIX_APK;
		final String filePath = UtilStorage.getFilePath(mActivity, fileName);

		cancel();
		//上一次已经下载了该安装包，并通过校验，则直接安装
		if(new File(filePath).exists() && UtilMD5.getFileMD5(filePath).equals(mInfo.getMd5())) {
			UtilPackage.installApk(mContext, filePath);

			if(mInfo.isForceUpdate()) {
				mActivity.finish();
			}
		} else {
			//进入下载对话框，下载升级应用
			if(mInfo.isForceUpdate()) {
				AppDownloadDialog dialog = new AppDownloadDialog(mActivity, mInfo);
				dialog.show();
			} else {
				//通知栏方式下载更新
				downloadApp();
			}
		}

	}


	/**
	 * 通知栏方式下载更新
	 */
	private void downloadApp() {
		String fileName = UtilMD5.getStringMD5(mInfo.getUrl()) + CstFile.SUFFIX_APK;
		final String filePath = UtilStorage.createFilePath(mActivity, fileName);

        OuerApplication.mOuerFuture.execDownloadFuture(mInfo.getUrl(), filePath,
				new OuerFutureListener(mActivity){

				@Override
				public void onStart(AgnettyResult result) {
					super.onStart(result);
					//开始
					nofityAppDownload(mActivity, 0);
				}

				@Override
				public void onProgress(AgnettyResult result) {
					super.onProgress(result);
					//更新进度
					int progress = result.getProgress();
					nofityAppDownload(mActivity, progress);
				}

				@Override
				public void onComplete(AgnettyResult result) {
					super.onComplete(result);
					cancelAppDownload(mContext);
					//下载完成，校验安装包，成功安装应用，否则删除该安装包
					if(UtilMD5.getFileMD5(filePath).equals(mInfo.getMd5())) {
						UtilPackage.installApk(mContext, filePath);
					} else {
						UtilFile.deleteFile(filePath);
					}
				}

				@Override
				public void onNetUnavaiable(AgnettyResult result) {
					super.onNetUnavaiable(result);
					//网络不给力
					cancelAppDownload(mContext);
				}

				@Override
				public void onException(AgnettyResult result) {
					super.onException(result);
					//下载过程发生异常
					UtilOuer.toast(mActivity, R.string.upgrade_download_failure);
					cancelAppDownload(mContext);
				}

			});

	}




	/**
	 * 通知安装包下载进度
	 * @param context	 上下文
	 * @param progress  下载进度
	 */
	private void nofityAppDownload(Context context, int progress) {
        Notification notification =  new NotificationCompat.Builder(context)
        	.setContentTitle(context.getString(R.string.upgrade_download_title))
        	.setContentText(context.getString(R.string.upgrade_download_progress, progress))
        	.setTicker(context.getString(R.string.upgrade_download_ticker))
        	.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT))
        	.setWhen(System.currentTimeMillis())
        	.setOngoing(true)
        	.setSmallIcon(R.drawable.common_ic_launcher)
        	.setDefaults(Notification.DEFAULT_LIGHTS)
        	.build();


        NotificationManager manager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(APP_DOWNLOAD_NOTIFY_ID, notification);
	}


	/**
	 * 取消下载通知
	 * @param context  上下文
	 */
	private void cancelAppDownload(Context context) {
		NotificationManager manager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancel(APP_DOWNLOAD_NOTIFY_ID);
	}



}

